import { ButtonProps } from 'element-plus'

import {
  getComponentProps,
  getComponentEvents,
  getComponentSlots,
  createDefaultEvent,
  type RenderFormItemContentOptions,
  type RenderFormItemContentParams,
  type ComponentParams
} from './common'

import { $t } from '@/locales'

const handleClick = (
  renderOpts: RenderFormItemContentOptions & { eventCode?: string },
  componentParams: ComponentParams
) => {
  const { name, eventCode } = renderOpts
  const { $form } = componentParams[0]
  // 组件挂载的params
  const { executeEvent } = componentParams[0].$form.props.params

  if (name === 'reset') {
    $form.reset()
  }

  executeEvent(eventCode || name, componentParams[0], componentParams[1])
}

const renderButtonItem = (
  renderOpts: RenderFormItemContentOptions,
  params: RenderFormItemContentParams
) => {
  // 默认属性
  const defaultProps = {} as Writable<ButtonProps>
  // 需要自定义的事件
  const omitEventsKeys = ['onClick']

  const { name } = renderOpts
  let content = renderOpts.content

  if (name === 'search') {
    content = content || $t('system.查询')
    defaultProps.type = 'primary'
    defaultProps.icon = 'Search'
  }

  if (name === 'reset') {
    content = content || $t('system.重置')
    defaultProps.icon = 'Refresh'
  }

  if (name === 'export') {
    content = content || $t('system.导出')
    defaultProps.icon = 'Download'
  }

  return (
    <el-button
      {...getComponentProps(renderOpts, defaultProps)}
      {...getComponentEvents(renderOpts, params, omitEventsKeys)}
      onClick={createDefaultEvent(renderOpts, params, 'click', handleClick)}
    >
      {content || { ...getComponentSlots(renderOpts) }}
    </el-button>
  )
}

const ActionButtons = {
  // 项内容模板
  renderItemContent(renderOpts: RenderFormItemContentOptions, params: RenderFormItemContentParams) {
    const { children } = renderOpts

    if (children) {
      return children.map((childRenderOpts) => renderButtonItem(childRenderOpts, params))
    }
    return []
  }
}

export default { ActionButtons }
